package cn.taobaoke

import cn.taobaoke.restful.ImportService
import cn.taobaoke.restful.datasource.CustomerDataSource
import cn.taobaoke.restful.datasource.DynamicDataSourceContextHolder
import cn.taobaoke.restful.datasource.DynamicDataSourceRegister
import cn.taobaoke.restful.domain.DomainRepository
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.boot.CommandLineRunner
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.web.servlet.ServletComponentScan
import org.springframework.context.ApplicationContext
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Import
import java.lang.Exception

val logger: Logger = LoggerFactory.getLogger(Application::class.java)

@SpringBootApplication
@ServletComponentScan
@Import(DynamicDataSourceRegister::class)
class Application {
    @Bean
    fun commandLineRunner(ctx: ApplicationContext): CommandLineRunner {
        return CommandLineRunner {
            val beanNames = ctx.beanDefinitionNames
            logger.info("Loading beans: ${beanNames.size}")
        }
    }
}

fun main(args: Array<String>) {

    val context = SpringApplication.run(Application::class.java, *args)

    context.getBean(CustomerDataSource::class.java).initCustomDataSources()

    DynamicDataSourceContextHolder.setDataSourceType("tbk_background")
    val repository = context.getBean(DomainRepository::class.java)
    val importService = context.getBean(ImportService::class.java)
    val domains = repository.findAll()
    DynamicDataSourceContextHolder.clearDataSourceType()

    domains.forEach {it -> try {
        importService.import2NewDatabase(it.domain, it.id)
    } catch (e: Exception) {
        logger.info("Failed to import [{}]", it.domain)
    }}

    System.exit(0)
}
